from stock.CatchData.operation import CatchData
from stock.CatchData.news import StockNews
from stock.Convert.csv_to_mongo import ConvertData
from stock.CatchData.newstock import StockCatchNew
import os,sys,time

def catch_h_data(lists):
    cd = CatchData()
    cv = ConvertData()
    for code in lists:
        cd.get_h_data_newer(code)
        file = "./" + code + ".csv"
        if not os.path.exists(file):
            continue
        print("convert from %s to %s" % (file, "history_" + code))
        cv.csv_to_mongo(file, "stock", "history_"+ code)
        #os.remove(file)

def catch_k_data(lists):
    cd = CatchData()
    cv = ConvertData()
    for code in lists:
        cd.get_k_data_e(code)
        file = "./" + code + ".csv"
        if not os.path.exists(file):
            continue
        print("convert from %s to %s" % (file, "history_" + code))
        cv.csv_to_mongo(file, "stock", "history_"+ code)
        os.remove(file)

def help():
    print("     -h                  This message")
    print("     news [num]          Get news, num how many news, default 30")
    print("     toptoday [date]     Get today max, date which day default today [YYYY-mm-DD]")
    print("     topmany [num]       Get num days max, num last days 5, 10, 30, 60")
    print("     todayall [date]     Get tokay all items date [YYYYmmDD]")
    print("     tickdata code [date] Get tick data of one day, default today [YYYY-mm-DD]")
    print("     concepts            Get conecpts")
    print("     area                Get areas")
    print("     companies           Get companies")
    print("     newdailytoday [date]          Get newdailytoday")
    print("     newdaily code [start] [end]           Get newdaily")
    print("     newbasic           Get newbasic")
    print("     newcompany           Get newcompany")
    print("     industry            Get industry")
    print("     historydata code    Get history code of one day")
    print("     newscontent url     Get news content with one url")
    print("     hs300 sz50s zz500s new_stocks             Get ")
    print("     fundholdings year quarter       Get fund holdings")
    print("     boxoffice realtime  Get box office no args")
    print("     reportdata/profitdata year month  Get report data of year and month(1-4)")

def time_str():
    return time.strftime("%Y%m%d")

def time_str_2():
    return time.strftime("%Y-%m-%d")

class switch(object):
     def __init__(self, value):
         self.value = value
         self.fall = False
 
     def __iter__(self):
         """Return the match method once, then stop"""
         yield self.match
         raise StopIteration
     
     def match(self, *args):
         """Indicate whether or not to enter a case suite"""
         if self.fall or not args:
             return True
         elif self.value in args: # changed for v1.5, see below
             self.fall = True
             return True
         else:
             return False

if __name__ == "__main__":
    if sys.argv[1] == "-h":
        help()
        exit(1)

    cd = CatchData()
    sn = StockNews()
    cv = ConvertData()
    nc = StockCatchNew(todb=False, tocsv=True)

    print("sys argv = " + sys.argv[1])
    for case in switch(sys.argv[1]):
        if case("topmany"):
            num = 5
            if len(sys.argv) > 2:
                num = int(sys.argv[2])
            name="topbefore_" + time_str() + "_" + str(num) + "days"
            print("Get to db name " + name)
            cd.get_topbefore(num, name)
            break

        if case("toptoday"):
            name=time_str_2()
            if len(sys.argv) > 2:
                name = sys.argv[2]
            print("Get top today to db name " + name)
            cd.get_toptoday(name, name.replace("-", "", -1))
            break

        if case("newdaily"):
            code = '0'
            if len(sys.argv) > 2:
                code = sys.argv[2]
            start_date = '19900101'
            if len(sys.argv) > 3:
                start_date = sys.argv[3]
            end_date = time_str()
            if len(sys.argv) > 4:
                end_date = sys.argv[4]
            print("get code ", code, ", start = ", start_date, ", end = ", end_date)
            nc.getDaily(code, start_date, end_date)
            exit()
        if case("newindex"):
            code = '0'
            if len(sys.argv) > 2:
                code = sys.argv[2]
            start_date = '19900101'
            if len(sys.argv) > 3:
                start_date = sys.argv[3]
            end_date = time_str()
            if len(sys.argv) > 4:
                end_date = sys.argv[4]
            print("get code ", code, ", start = ", start_date, ", end = ", end_date)
            nc.getIndexDaily(code, start_date, end_date)
            exit()
        if case("probar"):
            code = '0'
            if len(sys.argv) > 2:
                code = sys.argv[2]
            start_date = '19900101'
            if len(sys.argv) > 3:
                start_date = sys.argv[3]
            end_date = time_str()
            if len(sys.argv) > 4:
                end_date = sys.argv[4]
            print("get code ", code, ", start = ", start_date, ", end = ", end_date)
            nc.getProBar(code, start_date, end_date)
            exit()
        if case('newtrade'):
            tt = time_str()
            if len(sys.argv) > 2:
                tt = sys.argv[2]
            print("get trade of ", tt)
            nc.getDailyTrade(tt)
            exit()
        if case("newdailytoday"):
            tt = time_str()
            if len(sys.argv) > 2:
                tt = sys.argv[2]
            print("get date of ", tt)
            nc.getDailyToday(tt)
            exit()
        if case("newbasic"):
            nc.getBasic()
            exit()
        if case("newcompany"):
            nc.getCompany()
            exit()
        if case("limitlist"):
            tt = time_str()
            if len(sys.argv) > 2:
                tt = sys.argv[2]
            print("get limit list of ", tt)
            nc.getLimitList(tt)
            exit()
        if case("newdailyfull"):
            tt = time_str()
            if len(sys.argv) > 2:
                tt = sys.argv[2]
            print("get daily full of ", tt)
            nc.get_daily_full(tt)
            exit()

    print("next judge")
    if sys.argv[1] == "news":
        counts = 30
        if len(sys.argv) > 2:
            counts = sys.argv[2]
        print("Get news of counts ", counts)
        news = sn.get_news(counts)
        sn.print_news(news)

    # get hist data of code
    elif sys.argv[1] == "historydata":
        code=sys.argv[2]
        print("Get history data of code " + code)
        codelist = []
        codelist.append(code)
        catch_h_data(codelist)

    elif sys.argv[1] == "todayall":
        name=time_str()
        if len(sys.argv) > 2:
            name = sys.argv[2]
        name = name.replace("-", "", -1)
        print("Get today all of name " + name)
        cd.get_today_data(name)

    elif sys.argv[1] == "kdata":
        code = sys.argv[2]
        print("Get kdata of code " + code)
        codelist = []
        codelist.append(code)
        catch_k_data(codelist)

    elif sys.argv[1] == "concepts":
        print("Get Concepts")
        cd.get_concepts();

    elif sys.argv[1] == "area":
        print("Get Areas")
        cd.get_areas()

    elif sys.argv[1] == "industry":
        print("Get industry")
        cd.get_classified()

    elif sys.argv[1] == "companies":
        print("Get Companies")
        cd.get_companies()
        #file="./companies.csv"
        #cv = ConvertData()
        #cv.csv_to_mongo_default(file, "stock", "companies")
        #os.remove(file)

    elif sys.argv[1] == "newscontent":
        url=sys.argv[2]
        content = sn.get_news_content(url)
        print(content)

    elif sys.argv[1] == "hs300":
        cd.get_hs300()

    elif sys.argv[1] == "sz50s":
        cd.get_sz50s()

    elif sys.argv[1] == "zz500s":
        cd.get_zz500s()

    elif sys.argv[1] == "new_stocks":
        cd.get_new_stocks()

    elif sys.argv[1] == "reportdata":
        year = sys.argv[2]
        mon = sys.argv[3]
        cd.get_report_data(year, mon)

    elif sys.argv[1] == "profitdata":
        year = sys.argv[2]
        mon = sys.argv[3]
        cd.get_profit_data(year, mon)

    elif sys.argv[1] == "tickdata":
        code = sys.argv[2]
        datet = time_str_2()
        if len(sys.argv) > 3:
            datet = sys.argv[3]
        filedata = datet.replace("-", "", -1)
        csv_file = "./tick_" + code + "_" + filedata + ".csv"
        print("Get code %s date %s to file %s " % (code, datet, csv_file))
        cd.get_tick_data(code, datet, csv_file)
        coll_name = "tick_" +filedata+"_"+code
        cv = ConvertData()
        cv.csv_to_mongo_no_remove(csv_file, "stock", coll_name)
        os.remove(csv_file)

    elif sys.argv[1] == "fundholdings":
        if len(sys.argv) < 4:
            print("Usage: see -h")
            exit()
        year = sys.argv[2]
        quarter = sys.argv[3]
        cd.get_fund_hodings(year, quarter)

    elif sys.argv[1] == "boxoffice":
        cd.get_boxoffice_realtime()

    else:
        print("Unsupport function " + sys.argv[1])
        exit()
